package xyz.zchao.blog.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import xyz.zchao.blog.annotation.IgnoreToken;
import xyz.zchao.blog.pojo.Notice;
import xyz.zchao.blog.service.NoticeService;
import xyz.zchao.blog.util.PageResultVO;
import xyz.zchao.blog.util.ResultCode;
import xyz.zchao.blog.util.ResultVO;

import javax.validation.Valid;
import java.util.List;

/**
 * @Description:
 * @Author: guozongchao
 * @Date: 2020/5/17 1:00
 */
@RestController
@RequestMapping("/notice")
public class NoticeController {
    @Autowired
    private NoticeService noticeService;

    @IgnoreToken
    @GetMapping("/list")
    public PageResultVO getNotices(@RequestParam(required = false) Integer page, @RequestParam(required = false) Integer limit) {
        List<Notice> notices = noticeService.retrieveAllByPaging(page, limit);
        long count = noticeService.getCount();
        return new PageResultVO(ResultCode.SUCCESS, notices, count);
    }

    @IgnoreToken
    @GetMapping("/list/{nid}")
    public ResultVO getNotice(@PathVariable("nid") Integer nid) {
        Notice notice = noticeService.retrieveById(nid);
        return new ResultVO(ResultCode.SUCCESS, notice);
    }

    @PutMapping("/list/{nid}")
    public ResultVO updateNotice(@PathVariable("nid") Integer nid, @RequestBody @Valid Notice record) {
        record.setNoticeId(nid);
        noticeService.update(record);
        return new ResultVO(ResultCode.SUCCESS, null);
    }

    @DeleteMapping("/list/{nid}")
    public ResultVO deleteNotice(@PathVariable("nid") Integer nid) {
        noticeService.deleteById(nid);
        return new ResultVO(ResultCode.SUCCESS, null);
    }

    @PostMapping("/add")
    public ResultVO addNotices(@RequestBody @Valid Notice record) {
        noticeService.create(record);
        return new ResultVO(ResultCode.SUCCESS, null);
    }

    @IgnoreToken
    @GetMapping("/search")
    public ResultVO searchNotices(@RequestParam String keyword) {
        List<Notice> notices = noticeService.findNoticeByKeyword(keyword);
        return new ResultVO(ResultCode.SUCCESS, notices);
    }
}
